const fs = require("fs");
const path = require("path");
const prompts = require("prompts");
const Client = require("ssh2-sftp-client");
const client = new Client();

const targetInfo = {
  host: "192.168.31.237",
  port: "22",
  username: "root",
  password: "123456",
  targetDir: "/usr/local/mes-55",
};

// 定义打包列表
const targetList = [
  {
    name: "basic-web",
    sourceName: "basic-web.rar",
  },
  {
    name: "mes-web",
    sourceName: "mes-web.rar",
  },
  {
    name: "mes-op-web",
    sourceName: "mes-op-web.rar",
  },
];

// 询问用户选择需要打包的应用
(async () => {
  const response = await prompts({
    type: "select",
    name: "selectedApp",
    message: "请选择需要上传的应用：",
    choices: targetList.map((app) => ({ title: app.name, value: app.name })),
  });

  const selectedApp = targetList.find(
    (app) => app.name === response.selectedApp
  );

  if (selectedApp) {
    console.log("选择的应用:", selectedApp.name);
    uploadArchive(selectedApp);
  } else {
    console.log("选择的应用不存在.");
  }
})();

// 创建压缩包函数
function uploadArchive(app) {
  const sourceFileName = path.join(
    require("os").homedir(),
    "Desktop",
    app.sourceName
  );
  // 将应用上传至服务器;
  client
    .connect(targetInfo)
    .then((result) => {
      console.log(
        "开始上传资源包",
        `${targetInfo.targetDir}/${app.sourceName}`
      );
      return client.put(
        sourceFileName,
        `${targetInfo.targetDir}/${app.sourceName}`
      );
    })
    .then(() => {
      console.log("文件上传成功.");
      // client.end();
    })
    .catch((err) => {
      console.error("文件上传失败:", err.message);
      // client.end();
    });
}
